<template>
  <view class="payment-container">
    <!-- 遮罩层 -->
    <view class="popup" @click="onClickOperate($event, 'close', {})"> </view>

    <view class="payment-module">
      <view class="todo" v-if="activityType != 'freight'">
        支付成功后请在背包中手动发货
      </view>

      <!-- 头部 -->
      <view class="top">
        <view class="title"
          >支付订单
          <view class="time"
            >(
            <u-count-down
              ref="uCountDown"
              :show-days="false"
              :show-hours="false"
              :show-minutes="true"
              :timestamp="details.auto_close_time * 1"
              separator-color="#fb6497"
              color="#fb6497"
              @end="onEnd"
            ></u-count-down>
            )</view
          >
        </view>
        <img
          class="close-icon"
          src="/static/images/back-1.png"
          alt=""
          @click="onClickOperate($event, 'close', {})"
        />
      </view>
      <!-- 金额 -->
      <view class="price">
        <view>
          ￥
          <text class="count"
            >{{ amount[0] }} <text class="mini">.{{ amount[1] }}</text></text
          ></view
        >
      </view>
      <!-- 支付信息 -->
      <view class="cell-group">
        <view class="label"> {{ orderName[activityType] }}原价</view>
        <view class="value">￥{{ details.original_amount }}</view>
      </view>
      <view
        class="cell-group"
        v-if="details.discounts_amount || (activeCoupon && activeCoupon.amount)"
      >
        <view class="label">优惠金额 </view>
        <view class="value"
          >￥{{
            activeCoupon && activeCoupon.amount
              ? activeCoupon.amount
              : details.discounts_amount
          }}</view
        >
      </view>
      <view class="cell-group">
        <view class="label">使用优惠券 </view>
        <view class="value" @tap="selectCanUseCoupon">
          {{ coupon.total > 0 ? coupon.total + '张可用' : '暂无优惠券' }}
          <u-icon class="i" name="arrow-right"></u-icon
        ></view>
      </view>
      <!-- 分割线 -->
      <view class="page"></view>
      <!-- 积分支付 -->
      <view class="payment-other">
        <view class="left-content">
          <img class="icon" src="/static/images/bit.png" />
          <view class="cell">
            <view class="title"> 积分支付 </view>
            <view class="text">
              当前积分：￥{{ details.money || 0 }}，使用积分支付￥{{
                amount[0]
              }}.{{ amount[1] }}</view
            >
          </view>
        </view>
        <view class="right-check">
          <u-checkbox
            class="checkbox-r"
            size="40"
            active-color="#fb6497"
            v-model="checkedBalance"
            shape="circle"
          >
            <view class="float-btn"> </view>
          </u-checkbox>
          <!-- <u-icon class="i-check" name="checkmark-circle-fill"></u-icon> -->
        </view>
      </view>
      <!-- 购买须知 -->
      <view class="payment-other" v-if="activityType != 'freight'">
        <view class="left-content">
          <view class="cell">
            <view class="title"> 购买须知 </view>
            <view class="text">
              我已阅读并同意
              <text class="inset" @tap="onClickOperate($event, 'explain')"
                >《爱特玩买家须知》</text
              >
            </view>
          </view>
        </view>
        <view class="right-check">
          <u-checkbox
            size="40"
            active-color="#fb6497"
            v-model="checkedIllustrate"
            shape="circle"
          >
            <view class="float-btn"> </view>
          </u-checkbox>
        </view>
      </view>

      <view class="pay-group">
        <view
          class="btn"
          :class="checkedIllustrate ? 'can' : ''"
          hover-class="hover-bubble"
          @tap="onPay"
        >
          <image class="btn-bg" :src="btnImg" mode="widthFix" />
          <view class="btn-t"> 立即支付 </view>
        </view>
      </view>
    </view>

    <u-popup
      mode="bottom"
      border-radius="20"
      closeable
      v-model="showIllustrate"
    >
      <view class="content-illustrate">
        <scroll-view scroll-y="true" style="height: 60vh">
          <view v-html="illustrate"> </view>
        </scroll-view>
      </view>
    </u-popup>
  <!-- <shopro-use-coupon
      class="coupon"
      :show="openCoupon"
      :order_sn="details.order_sn"
      @useCoupon="onUseCoupon"
      @no-show="onNoShow"
    ></shopro-use-coupon> -->
  </view>
</template>
<script>
/**
 * 支付
 * @property {String|Number} activityType 订单类型 一番赏 福袋
 * @property {String|Number} activityId 活动id
 * @property {String|Number} rollNum 抽取 数量
 * @property {String|Number} boxId 箱子id
 * @method changePayMod 关闭支付弹窗
 * @method result 抽奖结果
 * @method payed 支付后
 *
 */

/**
 * 接收商品订单orderType:goods，充值订单orderType:recharge
 */
// import Pay from '@/shopro/pay';
// import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
// import wechat from '@/shopro/wechat/wechat';
import tools from '@/shopro/utils/tools';
const _delay = tools.delayDither(300);
import ShoproUseCoupon from '../shopro-coupon/shopro-use-coupon.vue';
export default {
  // 建议 创建每个组件时 都添加name属性 标识组件名称
  name: '',
  // components: { ShoproUseCoupon },
  props: {
    /* yfs 一番赏, luckybag 福袋, freight 运费 */
    activityType: {
      type: [String, Number],
      default: '',
    },
    // 规则id
    protocol: {
      type: [String, Number],
      default: '',
    },
    // 交易信息
    details: {
      type: Object,
      default: () => ({}),
    },
    history: {
      type: Object,
      default: () => ({
        type: '',
      }),
    },

    // activityId: {
    //   type: [String, Number],
    //   default: '',
    // },
    // rollNum: {
    //   type: [String, Number],
    //   default: '',
    // },
    // boxId: {
    //   type: [String, Number],
    //   default: '',
    // },
  },
  data() {
    return {
      active: 0,
      btnImg:
        this.$IMG_URL +
        '/uploads/20230609/08ceb59314776ff0e9e6a101482709d1.png',
      illustrate: '',

      orderName: {
        yfs: '订单',
        luckybag: '订单',
        freight: '运费',
        full_open: '订单',
        direct_goods: '订单',
      },
      activeCoupon: null,
      coupon: {
        list: [],
        total: 0,
      },
      // 开启关闭 购买须知
      showIllustrate: false,
      // 积分支付
      checkedBalance: false,
      // 选择勾选 协议
      checkedIllustrate: false,
      // 开启优惠券选择
      openCoupon: false,
    };
  },
  // 计算属性 适配者模式
  computed: {
    amount() {
      let price = this.details.total_amount || 0;
      if (
        this.activeCoupon &&
        this.activeCoupon.id &&
        this.activeCoupon.amount
      ) {
        price = price - this.activeCoupon.amount;
      }
      price = Number(price).toFixed(2);
      let arr = price.split('.');
      return arr;
    },
    payType() {
      return this.checkedBalance ? 'wallet' : 'wechat';
    },
    payHistory() {
      return this.history;
    },
  },
  // 数据监听
  watch: {},
  /**
   * 生命周期 类似 发布订阅者模式
   * 在实例初始化之前被调用
   */
  beforeCreate() {},
  // 在实例创建完成后被立即调用
  created() {
    // this.createOrder();
  },
  // 在挂载开始之前被调用
  beforeMount() {},
  // 挂载到实例上去之后调用。详见 注意：此处并不能确定子组件被全部挂载，如果需要子组件完全挂载之后在执行操作可以使用nextTick
  mounted() {
    if (this.payHistory?.type) {
      switch (this.payHistory?.type) {
        case 'wechat':
          this.checkedIllustrate = true;
          break;
        case 'wallet':
          this.checkedBalance = true;
          this.checkedIllustrate = true;
          break;
      }
    }
    if (this.activityType != 'freight') {
      this.getProtocol();
    } else {
      this.checkedIllustrate = true;
    }

    this.getnoUseCouponList();
  },
  // 数据更新时调用，发生在虚拟 DOM 打补丁之前
  beforeUpdate() {},
  // 由于数据更改导致的虚拟 DOM 重新渲染和打补丁，在这之后会调用该钩子
  updated() {},
  // 实例销毁之前调用。在这一步，实例仍然完全可用
  beforeDestroy() {},
  // Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，所有的事件监听器会被移除，所有的子实例也会被销毁。
  destroyed() {},
  methods: {
    /**
     *  页面点击事件 防抖
     * @param {Object} ev  $event
     * @param {String} name 执行名称
     * @param {Object} data 传值
     */
    onClickOperate(ev, name, data = {}) {
      _delay(() => {
        switch (name) {
          // 关闭弹窗
          case 'close':
            this.close(data);
            break;
          // 开启关闭 购买须知
          case 'explain':
            this.showIllustrate = !this.showIllustrate;
            break;
        }
      });
    },
    onEnd() {
      this.close();
    },
    // 关闭 弹窗
    close() {
      this.$emit('changePayMod', false);
    },

    // 获取购买须知
    getProtocol() {
      this.$http('v1.getProtocol', {
        id: '1',
      })
        .then((res) => {
          if (res.code === 1) {
            this.illustrate = res.data[0].content;
          }
        })
        .catch(() => {});
    },

    payResult(ev, result) {
      this.$emit('payed', { status: ev, result, type: this.payType });
    },

    //支付
    onPay() {
      if (!this.checkedIllustrate) return;

      let that = this;
      // 支付后
      const fn = (result) => {
        this.$emit('payed', result);
      };
      const err = (result) => {
        this.$emit('payed', result);
      };

      if (!that.payType) {
        this.$u.toast('请选择支付方式');
        return;
      }
      if (that.payType === 'wallet') {
        uni.showModal({
          title: '支付提示',
          confirmColor: '#f0c785',
          content: `是否确认使用积分支付:${that.amount[0]}.${that.amount[1]}元?`,
          success: (res) => {
            if (res.confirm) {
              this.walletPay();
            }
          },
        });
      } else {
        this.wxMiniProgramPay();
      }
    },
    // 积分支付
    async walletPay() {
      let that = this;
      let result = await this.prepay();
      result.data.order_sn = this.details.order_sn;
      result.code === 1 && this.payResult('success', { ...result });
    },

    // 微信小程序支付
    async wxMiniProgramPay() {
      let that = this;
      let result = await this.prepay();
      result.data.order_sn = this.details.order_sn;
      uni.requestPayment({
        provider: 'wxpay',
        ...result.data.pay_data,
        success: (res) => {
          this.payResult('success', result);
        },
        fail: (err) => {
          console.log('支付取消或者失败:', err);
          err.errMsg !== 'requestPayment:fail cancel' &&
            this.payResult('fail', res);
        },
      });
    },

    // 预支付
    prepay() {
      let that = this;
      return new Promise((resolve, reject) => {
        let that = this;
        let params = {
          order_sn: that.details.order_sn,
          payment: that.payType,
        };
        if (uni.getStorageSync('openid')) {
          params.openid = uni.getStorageSync('openid');
        } else {
        }
        if (this.activeCoupon?.id) {
          params.coupons_id = this.activeCoupon.id;
        }
        that.$http('v1.prepay', params, '支付中').then((res) => {
          if (res.code === 1) {
            res.data === 'no_openid'
              ? uni.showModal({
                  title: '微信支付',
                  content: '请先绑定微信再使用微信支付',
                  success: function (res) {
                    if (res.confirm) {
                      // wechat.bind();
                    }
                  },
                })
              : resolve(res);
          } else {
            reject();
          }
        });
      });
    },
    // 获取 可用优惠券
    getnoUseCouponList() {
      this.$http(
        'v1.getCouponList',
        {
          page: 1,
          use_status: 3,
          order_sn: this.details.order_sn,
        },
        '请稍等'
      ).then((res) => {
        if (res.code === 1) {
          this.coupon = res.data;
        }
      });
    },
    // 选择可用 优惠券
    selectCanUseCoupon() {
      if (this.coupon.total == 0) return;
      this.openCoupon = true;
    },
    // 使用 优惠券
    onUseCoupon(ev) {
      this.activeCoupon = ev;
      console.log('this.activeCoupon', this.activeCoupon);
    },
    // 显示关闭
    onNoShow(e) {
      this.openCoupon = e;
    },
  },
};
</script>
<style lang="scss" scoped>
.payment-container {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 100074;
  width: 100%;
  height: 100vh;
}
.popup {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
}
.coupon {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 11;
}
.payment-module {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 10;
  width: 100%;
  height: 1000rpx;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  animation: slide-in-bottom 1s linear 0s 1 normal none;

  .todo {
    padding: 30rpx 34rpx 24rpx 34rpx;
    width: 100%;
    background: #f9fafc;
    border-radius: 20rpx 20rpx 0 0;

    font-size: 22rpx;
    font-weight: 800;
    color: #fb6497;
  }

  .top {
    position: relative;
    display: flex;
    padding: 30rpx 30rpx 10rpx;
    width: 100%;
    .title {
      display: flex;
      align-items: center;
      font-size: 32rpx;
      font-weight: 800;
      color: #000000;

      .time {
        margin-left: 20rpx;
        font-size: 32rpx;
        font-weight: 800;
        color: #fb6497;
        .u-countdown-colon {
          color: #fb6497 !important;
        }
      }
    }
    .close-icon {
      box-sizing: content-box;
      position: absolute;
      top: 48rpx;
      right: 30rpx;
      padding: 0rpx 0 20rpx 20rpx;
      width: 32rpx;
      height: 18rpx;
    }
  }
  .price {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 210rpx;
    color: rgba(0, 0, 0, 1);
    font-size: 57rpx;
    .count {
      color: rgba(0, 0, 0, 1);
      font-size: 72rpx;
      .mini {
        font-size: 40rpx;
      }
    }
  }

  .cell-group {
    display: flex;
    justify-content: space-between;

    margin-bottom: 44rpx;
    padding: 0 30rpx;

    width: 100%;
    color: rgba(0, 0, 0, 1);
    font-size: 28rpx;
    font-weight: 600;
    .label {
    }
    .value {
      .i {
        margin-left: 8rpx;
        font-size: 18rpx;
      }
    }
  }

  .page {
    margin-bottom: 36rpx;
    padding: 0 30rpx;
    width: 100%;
    height: 2rpx;
    &::before {
      content: '';
      display: block;
      width: 100%;
      height: 2rpx;
      border-bottom: 2rpx dotted #707070;
    }
  }
  .payment-other {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    padding: 0 30rpx;
    .left-content {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 8rpx;
        width: 54rpx;
        height: 54rpx;
      }
      .cell {
        .title {
          margin-bottom: 4rpx;
          color: rgba(0, 0, 0, 1);
          font-size: 28rpx;
        }
        .text {
          font-size: 24rpx;
          font-weight: 800;
          color: #bbbbc3;
          .inset {
            color: rgba(136, 49, 252, 1);
          }
        }
      }
    }
    .right-check {
      display: flex;

      left: 4rpx;
      width: 40rpx;
      height: 40rpx;
      // border-radius: 50%;
      // overflow: hidden;
      .u-checkbox {
        display: flex;
      }
      // .checkbox-r {
      //   position: relative;
      // }
      .i-check {
        position: relative;
        z-index: 1;
        color: #fb6497;
        font-size: 36rpx;
      }
      .float-btn {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        width: 200rpx;
        height: 80rpx;
      }
    }
  }
  .pay-group {
    position: absolute;
    bottom: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    width: 100%;
    height: 75rpx;
    .btn.can {
      filter: grayscale(0%);
    }
    .btn {
      position: relative;
      width: 378rpx;
      height: 75rpx;
      transition: all 0.6s;
      filter: grayscale(100%);
      .btn-bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
      }
      .btn-t {
        position: relative;
        z-index: 1;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 97rpx;
        font-size: 28rpx;
        font-weight: 800;
        color: #ffffff;
      }
    }
  }
}

.content-illustrate {
  padding: 24rpx;
  text-align: center;
}
</style>
